package com.jn.retrofit.presenter;

import android.content.Context;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.jn.retrofit.common.WeakRrfHandler;
import com.jn.retrofit.contract.TrackingContract;
import com.jn.retrofit.entity.TrackingNum;
import com.jn.retrofit.http.GlobalRetrofitClient;
import com.jn.retrofit.service.TrackingService;
import com.jn.retrofit.utils.LogUtils;

import java.io.IOException;

import okhttp3.HttpUrl;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TrackingPresenter implements TrackingContract.ITrackingPresenter {
    public static final int HTTP_SUCCESS = 0;
    public static final int HTTP_FAIL = 1;
    private TrackingContract.ITrackingView mTrackingView;
    private Context mContext;
    private OkHttpClient mClient;

    public TrackingPresenter(TrackingContract.ITrackingView trackingView, Context context) {
        mTrackingView = trackingView;
        mContext = context;
        mClient = new OkHttpClient();
    }

    @Override
    public void getData(String trackingNumber) {//get 异步
        TrackingService service = GlobalRetrofitClient.getInstance().create(TrackingService.class);
        service.getData(trackingNumber).enqueue(new Callback<TrackingNum>() {
            @Override
            public void onResponse(Call<TrackingNum> call, Response<TrackingNum> response) {
                Message message = Message.obtain();
                message.obj = response.body();
                message.what = HTTP_SUCCESS;
                mHandler.sendMessage(message);
            }

            @Override
            public void onFailure(Call<TrackingNum> call, Throwable t) {

            }
        });
    }

    WeakRrfHandler<TrackingPresenter> mHandler = new WeakRrfHandler<>(Looper.getMainLooper(), this, new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            int result = msg.what;
            switch (result) {
                case HTTP_SUCCESS:
                    TrackingNum trackingNum = (TrackingNum) msg.obj;
                    if (mTrackingView != null) {
                        mTrackingView.showData(trackingNum);
                    }
                    break;
                case HTTP_FAIL:
                    break;
            }
            return false;
        }
    });
}